package com.hzit.order.service.impl;

import com.hzit.common.resp.GoodsInfo;
import com.hzit.common.resp.Resp;
import com.hzit.order.config.OrderConfig;
import com.hzit.order.iclient.IGoodsClient;
import com.hzit.order.resp.OrderDetail;
import com.hzit.order.resp.OrderInfo;
import com.hzit.order.service.IOrderService;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;
import org.springframework.web.client.RestTemplate;

import java.util.ArrayList;
import java.util.List;

@Service
public class OrderServiceImpl implements IOrderService {

    /**
     * 模拟http请求
     */
    @Autowired
    private RestTemplate restTemplate;

    @Autowired
    private OrderConfig orderConfig;


    @Autowired
    private IGoodsClient  goodsClient;


    //code
    //msg
    // data

    @Override
    @HystrixCommand(fallbackMethod = "createOrderFallBack")
    public OrderInfo createOrder() {

        OrderInfo  orderInfo = new OrderInfo();

        //分布式系统中如何生成唯一id
        orderInfo.setOrderId(String.valueOf(System.currentTimeMillis()));


        List<OrderDetail> orderDetailList = new ArrayList<OrderDetail>();

        OrderDetail orderDetail = new OrderDetail();


//        String url = orderConfig.getUrl() + "/1";

        String url = "http://GOODS/goods/queryById/1";
        // 同步调用，阻塞，超时异常
        orderDetail = restTemplate.getForObject(url,OrderDetail.class);

        System.out.println("--orderDetail - = " + orderDetail);


        orderDetailList.add(orderDetail);

        orderInfo.setDetailList(orderDetailList);

        return orderInfo;
    }




    public OrderInfo createOrderFallBack(){

        return  new OrderInfo();
    }



    @Override
    public OrderInfo createOrder1() {
        OrderInfo  orderInfo = new OrderInfo();
        orderInfo.setOrderId(String.valueOf(System.currentTimeMillis()));

        Resp<GoodsInfo> resp = goodsClient.queryGoods("1");
        
        System.out.println("=======resp  = " + resp);


        System.out.println("--orderDetail - = " + resp.getT());

        List<OrderDetail> orderDetailList = new ArrayList<OrderDetail>();


        OrderDetail orderDetail = new OrderDetail();

        if(!ObjectUtils.isEmpty(resp.getT())){
            //复制javabean， 字段和内容要一样
            BeanUtils.copyProperties(resp.getT(),orderDetail);
        }

        orderDetailList.add(orderDetail);
        orderInfo.setDetailList(orderDetailList);
        return orderInfo;
    }
}
